package com.shiku.imserver.message.hander;

import com.shiku.imserver.CoreService;
import com.shiku.imserver.cluster.ImClusterServiceIfc;
import com.shiku.imserver.common.annotation.MessageCommandAnnotation;
import com.shiku.imserver.common.hander.AbstractMessageHandler;
import com.shiku.imserver.common.message.AuthMessage;
import com.shiku.imserver.common.message.AuthRespMessage;
import com.shiku.imserver.common.message.PacketVO;
import com.shiku.imserver.common.packets.ImPacket;
import com.shiku.imserver.common.proto.MessageProBuf;
import com.shiku.imserver.common.utils.ProBufUtils;
import com.shiku.imserver.common.utils.StringUtils;
import com.shiku.imserver.listener.ImServerListener;
import com.shiku.imserver.message.MessageFactory;
import com.shiku.imserver.service.IMBeanUtils;
import com.shiku.utils.StringUtil;

import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
@Slf4j
public class UserMessageHandler extends AbstractMessageHandler {
//    private static final Logger logger = LoggerFactory.getLogger(UserMessageHandler.class);

    @MessageCommandAnnotation(command = 5)
    public PacketVO authMessageHandler(ImPacket packet, ChannelContext channelContext) {
        if (packet == null) {
            try {
                log.info("authMessageHandler packet is null ");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        AuthMessage message = (AuthMessage) ProBufUtils.decoderMessageBody(packet.getBytes(), MessageProBuf.AuthMessage.getDescriptor(), AuthMessage.class);
        if (message == null) {
        	log.info("authMessageHandler message is null ");
        }
        String from = message.getMessageHead().getFrom();
        log.info("user auth userId > {} ", from);
        message.getMessageHead().getTo();
        String password = message.getPassword();
        String token = message.getToken();
        AuthRespMessage authResp = new AuthRespMessage();
        authResp.setMessageHead(MessageFactory.copyeMessageHead(message.getMessageHead()));
        authResp.getMessageHead().setChatType((byte) 10);
        String userId = CoreService.parseBareUserId(from);
        String resource = CoreService.parseResource(from);
        if (StringUtil.isEmpty(password) && !"mp".equals(resource)) {
            if ("Server".equals(resource)) {
                Tio.bindToken(channelContext, token);
                if (!IMBeanUtils.getImconfig().getServerToken().equals(token)) {
                	log.warn(" {} token  认证失败  {}  ", from, token);
                    authResp.setStatus((byte) 0);
                    authResp.setArg("im 认证失败 ! ");
                    return MessageFactory.createAuthRespPacket(authResp);
                }
            } else {
                Tio.bindToken(channelContext, token);
                String tokenUserId = IMBeanUtils.getRedisService().getUserIdByToken(token);
                if (StringUtils.isEmpty(tokenUserId) || !tokenUserId.equals(userId)) {
                	log.warn(" {} token  认证失败  {}  ", from, token);
                    authResp.setStatus((byte) 0);
                    authResp.setArg("im 认证失败 ! ");
                    return MessageFactory.createAuthRespPacket(authResp);
                }
            }
        }
//        ChannelContext channelContext2 = CoreService.getChannelContextByUserIdResource(channelContext.groupContext, userId, resource);
//        if (channelContext2 != null && !channelContext2.getId().equals(channelContext.getId())) {
//            String errArg = from + " 已经登陆  被挤下线 channelContext2.getId()="+channelContext2.getId()+",channelContext.getId()="+channelContext.getId();
//            log.info(errArg);
//            CoreService.notifyUserConflict(channelContext2, from, errArg);
//        }
        if (!StringUtils.isEmpty(resource)) {
            channelContext.setAttribute("resource", resource);
        }
        Tio.bindUser(channelContext, userId);
        String resources = StringUtils.listToString(CoreService.getChannelContextResources(channelContext.groupContext, userId), ",");
        authResp.setStatus((byte) 1);
        authResp.setToken(token);
        authResp.setResources(resources);
        Tio.sendToUser(channelContext.groupContext, userId, MessageFactory.createAuthRespIMPacket(authResp));
        CoreService.userOnline(from, userId, channelContext);

        ImClusterServiceIfc imClusterService = IMBeanUtils.getBeanManager().getImClusterService();
        if (imClusterService != null) {
            imClusterService.notifyClusterUserStatus(userId, resource, true);
        }
        return null;
    }

    @MessageCommandAnnotation(command = 1)
    public PacketVO onAfterHandshakedHandler(ImPacket packet, ChannelContext channelContext) {
        try {
            if (packet.getBytes() != null) {
            	log.info(" param ====> " + new String(packet.getBytes()));
                Tio.send(channelContext, new ImPacket("111111111111".getBytes()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
